/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.sll.service.catalogue.composite.camel.processor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Exchange;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import se.sll.service.catalogue.offers.api.model.OfferUnitList;
import se.sll.service.catalogue.offers.api.model.Product;
import se.sll.service.catalogue.offers.api.model.ProductReference;

/**
 *
 * @author khaleddaham
 */
@Slf4j
public class ProductProcessor {

    /**
     * JSON mapper for Product
     *
     * @param exchange
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    public void productResponseJSON(Exchange exchange) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        List<Product> responses = new ArrayList<>();
        try {
            responses = mapper.readValue(exchange.getIn().getBody(String.class), new TypeReference<List<Product>>() {
            });
        } catch (Exception e) {

        }
        exchange.getIn().setBody(responses);
    }

    /**
     * Builds up a queryParam and sets it as a header param for the HTTP
     * component
     *
     * @param exchange
     */
    @SuppressWarnings("unchecked")
    public void buildProductNameQueryParam(Exchange exchange) {
        List<OfferUnitList> offers = (List<OfferUnitList>) exchange.getIn().getBody();
        String queryParam = "";
        if (offers.isEmpty()) {
            exchange.getOut().getHeaders().put(Exchange.HTTP_QUERY, queryParam);
            log.info("Empty list of offers.");
            return;
        }
        for (OfferUnitList o : offers) {
            for (ProductReference pr : o.getProductReferences()) {
                queryParam = queryParam + "productName=" + pr.getProduct().getName() + "&";
            }
        }
        queryParam = queryParam.substring(0, queryParam.length() - 1);
        exchange.getOut().getHeaders().put(Exchange.HTTP_QUERY, queryParam);
    }
}
